<?php
namespace Crm\Domain;

use Crm\Common\MetaData as MetaData;
use Crm\Common\Util as Util;
use Crm\Common\Pager as Pager;

class Task
{
	/**
	 * ado连接。
	 * 
	 * @var object
	 * @access pdo
	 */
	public $pdo;

    public $metaData;
    public $baseCode;
    public $city_code;
    public $provinceCode;

    public function __construct()
    {
        $this->pdo = \PhalApi\DI()->pdo;
        $this->baseCode = (object)\PhalApi\DI()->config->get('basecode');
        $this->province_code = \PhalApi\DI()->config->get('app.provinceCode');//省
        $this->city_code = \PhalApi\DI()->config->get('app.cityCode');//城市

        $this->metaData = new MetaData();
    }

    public function search($data,$user){
        $this->session = (object)$user;
        $by = trim(isset($data["by"])?$data["by"]:'all');
        $status = trim(isset($data["status"])?$data["status"]:'');
        $date = trim(isset($data["date"])?$data["date"]:'');
        $flag = isset($data['flag'])?$data['flag']:1;
        $page_info = "";
        $orderField = isset($data['sort']) ? $data['sort'] : 'id';
        $orderValue = isset($_GET['sort_value']) ? $_GET['sort_value'] : 'desc';

        $pageSize = 15;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where 1=1 and flag='.$flag.' and city_code ='.$this->city_code.' ';

        $filter = array();//筛选条件
        $filter['by'] = $by;
        $filter['sort'] = $orderField;
        $filter['sort_value'] = $orderValue;
        $filter['status'] = $status;
        $filter['date'] = $date;
        $filter['flag'] = $flag;
        $page_info .="sort=".$orderField."&sort_value=".$orderValue."&by=".$by."&";

        switch ($by) {
            case 'create' :
                $where .= " and create_uid=".$this->session->user_id." ";
                break;
            case 'me' :
                $where .= 'and (owner_uid like "%,'.$this->session->user_id.',%" OR about_uid like "%,'.$this->session->user_id.',%") ';
                break;
            default:
                if(!isset($data['action_id']))
                $where .= 'and (create_uid='.$this->session->user_id.' OR owner_uid like "%,'.$this->session->user_id.',%" OR about_uid like "%,'.$this->session->user_id.',%") ';
                break;
        }

        switch ($status) {
            case 's0' :
                $where .= " and status=0 ";
                break;
            case 's1' :
                $where .= " and status=1 ";
                break;
            case 's2' :
                $where .= " and status=2 ";
                break;
            case 's3' :
                $where .= " and status=3 ";
                break;
            case 's4' :
                $where .= " and status=9 ";
                break;
            case 's5' :
                $where .= " and (status=3 or status=9) ";
                break;
            default :
                $where .= " and status<>3 and status<>9 ";
                break;
        }
        $page_info .="status=".$status."&";

        switch ($date) {
            case 'today' :
                $where .=  " and create_date>".(strtotime(date('Y-m-d'))-1)." and create_date<".(strtotime(date('Y-m-d'))+86400);
                break;
            case 'week' :
                $week = (date('w') == 0)?7:date('w');
                $where .=  " and create_date>".(strtotime(date('Y-m-d')) - ($week-1) * 86400 -1)." and create_date<".(strtotime(date('Y-m-d')) + (8-$week) * 86400);
                break;
            case 'month' :
                $next_year = date('Y')+1;
                $next_month = date('m')+1;
                $month_time = date('m') ==12 ? strtotime($next_year.'-01-01') : strtotime(date('Y').'-'.$next_month.'-01');
                $where .=  " and create_date>".(strtotime(date('Y-m-01')) -1)." and create_date<".$month_time;
                break;
            default :
                break;
        }

        //处理搜索条件
        $key = trim(isset($data["key"])?$data["key"]:"");
        if($key!=""){
            $where .= " and subject like '%".$key."%'";
            $page_info .="key=".$key."&";
        }

        //类型
        $type = isset($data['type'])?$data['type']:'';
        if($type!=''){
            $where .= " and type = '".$type."' ";
            $page_info .="type=".$type."&";
            $filter['type'] = $type;
            $filter['type_value'] = '全部';
        }else{
            $filter['type'] = $type;
            $filter['type_value'] = '任务相关类型';
        }

        //任务主体ID(action_id)
        $action_id = isset($data['action_id'])?$data['action_id']:0;
        if($action_id!=0){
            $where .= " and action_id = ".$action_id." ";
            $page_info .="action_id=".$action_id."&";
        }

        //任务子类
        $subtype = trim(isset($data["subtype"])?$data["subtype"]:"");
        if($subtype!=""){
            $where .= " and subtype = ".$subtype;
            $page_info .="subtype=".$subtype."&";
        }

        $select_columns = "select %s from crm_task %s %s %s";

        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(id) as count ";
        $sql = sprintf($select_columns,'*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns,$count,$where,'','');
        $res = $this->pdo->getAll($sql);

        //任务对象
        $sysUser = new SysUser();
        foreach ($res as $key=>$Info){
            //创建者
            $create_user = $sysUser->getUserNameById($Info['create_uid']);
            $res[$key]['create_name'] = $create_user['true_name'];

            //拥有者
            $owner_user = $sysUser->getUserNameById($Info['owner_uid']);
            if(count($owner_user) == count($owner_user, 1)){//判断是否多维数组
                $res[$key]['owner_name'] = $owner_user['true_name'];
            }else{
                foreach ($owner_user as $item){
                    $res[$key]['owner_name'] .= $item['true_name'].',';
                }
                $res[$key]['owner_name'] = substr($res[$key]['owner_name'],0,-1);
            }

            //相关者
            if(!empty($Info['about_uid'])){
                $about_user = $sysUser->getUserNameById($Info['about_uid']);
                if(count($owner_user) == count($owner_user, 1)){////判断是否多维数组
                    $res[$key]['about_name'] = $owner_user['true_name'];
                }else{
                    foreach ($about_user as $item){
                        $res[$key]['about_name'] .= $item['true_name'].',';
                    }
                    $res[$key]['about_name'] = substr($res[$key]['about_name'],0,-1);
                }
            }
            //任务相关
            $res[$key]['type_val'] = $this->baseCode->task_type_option[$Info['type']];
            //任务状态
            $res[$key]['status_val'] = $this->baseCode->task_status_option[$Info['status']];
            $res[$key]['status_color'] = Util::statusColor($Info['status']);
            //任务发起时间
            $res[$key]['create_date'] = date('Y-m-d H:i:s',$Info['create_date']);
            //任务结束时间
            $res[$key]['end_date'] = Util::dueDate($Info['due_date']);
            //任务最后一次跟进时间
            $log_sql = "select b.create_date from crm_r_task_log as a LEFT JOIN  crm_log as b on a.log_id=b.id and a.task_id=".$Info['id']." ORDER BY b.id desc limit 0,1";
            $log_date = $this->pdo->getRow($log_sql);
            if($log_date['create_date']!='')$res[$key]['log_date'] = date('Y-m-d H:i',$log_date['create_date']);
        }
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        $page=new Pager($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();
        $result['list'] = $res;
        $result['pageStr'] = $splitPageStr;
        $result['filter'] = $filter;
        $result['page_info'] = $page_info;

        return $result;
    }

    /* 获取任务详情 */
    public function getTaskBaseInfo($task_id){
        $task_id = intval($task_id);
        if($task_id>0){
            $sql = "select * from crm_task where id={$task_id}";
            $Info = $this->pdo->getRow($sql);
        }else{
            $Info = false;
        }
        return $Info;
    }

    /* 获取任务详情 */
    public function getTaskInfo($task_id){
        $task_id = intval($task_id);
        if($task_id>0){
            $sql = "select * from crm_task where id={$task_id}";
            $Info = $this->pdo->getRow($sql);

            $this->loadModel('sys_user');
            //创建者
            $create_user = $this->sys_user->getUserNameById($Info['create_uid']);
            $Info['create_name'] = $create_user['true_name'];
            //拥有者
            $owner_user = $this->sys_user->getUserNameById($Info['owner_uid']);
            if(count($owner_user) == count($owner_user, 1)){//判断是否多维数组
                $Info['owner_name'] = $owner_user['true_name'];
            }else{
                foreach ($owner_user as $item){
                   $Info['owner_name'] .= $item['true_name'].',';
                }
                $Info['owner_name'] = substr($Info['owner_name'],0,-1);
            }
            //相关者
            if(!empty($Info['about_uid'])) {
                $about_user = $this->sys_user->getUserNameById($Info['about_uid']);
                if (count($owner_user) == count($owner_user, 1)) {////判断是否多维数组
                    $Info['about_name'] = $owner_user['true_name'];
                } else {
                    foreach ($about_user as $item) {
                        $Info['about_name'] .= $item['true_name'] . ',';
                    }
                    $Info['about_name'] = substr($Info['about_name'], 0, -1);
                }
            }
            //任务相关
            $Info['type_val'] = $this->config->task_type_option[$Info['type']];
            //到期时间
            $Info['due_date_val'] = date('Y-m-d H:i:s',$Info['due_date']);
            $Info['end_date'] = Util::dueDate($Info['due_date']);
            //创建时间
            $Info['create_date_val'] = date('Y-m-d H:i:s',$Info['create_date']);
            //状态
            $Info['status_val'] = $this->baseCode->task_status_option[$Info['status']];
            $Info['status_color'] = Util::statusColor($Info['status']);
            //优先级
            $Info['priority_val'] = $this->config->task_priority_option[$Info['priority']];
        }else{
            $Info = false;
        }
        return $Info;
    }

    /* 任务推荐(状态转变) */
    public function advanceTaskStatus($task_id,$status,$msg){
        $param['status'] = $status;
        $rlt = $this->pdo->update($param,'crm_task','id='.$task_id);
        return $rlt;
    }

    /* 获取任务跟进日志 */
    public function getTaskFollow($data){
        $id = intval(isset($data["id"])?$data["id"]:0);
        $by = trim(isset($data["by"])?$data["by"]:'all');
        $page_info = "id=".$id."&";
        $orderField = isset($data['sort']) ? $data['sort'] : 'a.id';
        $orderValue = isset($data['flag']) ? $data['flag'] : 'desc';

        $pageSize = 10;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;
        $where = 'where b.flag=1 and a.task_id='.$id.' ';

        switch ($by) {
            //case 'today' : $where .= ' create_date='.strtotime(date('Y-m-d', time())) ; break;
            //case 'week' : $where['create_time'] =  array('gt',(strtotime(date('Y-m-d')) - (date('N', time()) - 1) * 86400)); break;
            //case 'month' : $where['create_time'] = array('gt',strtotime(date('Y-m-01', time()))); break;
            //case 'add' : $order = 'create_time desc'; break;
            //case 'update' : $order = 'update_time desc'; break;
            //case 'sub' : $where['owner_role_id'] = array('in',implode(',', $below_ids)); break;
            //case 'deleted' : $where['is_deleted'] = 1;break;
            case 'me' :
                $where .= "and b.create_uid=".$this->session->user_id." ";
                $page_info .= "by=".$by."&";
                break;
            //case 'focus' : $where['customer_id'] = array('in',$focus_id);break;
            //case 'share' : $where['customer_id'] = array('in',$customerid);break;
            //case 'myshare' : $where['customer_id'] = array('in',$share_customer_ids);break;
            default :
                break;
        }
        $select_columns = "select %s from crm_r_task_log as a LEFT JOIN crm_log as b on a.log_id=b.id %s %s %s";
        $order = "order by $orderField $orderValue";
        $limit = "limit $offset,$pageSize";
        $count = " count(a.id) as count ";
        $sql = sprintf($select_columns,'b.*',$where,$order,$limit);
        $sqlcount = sprintf($select_columns, $count,$where,'','');
        $res = $this->pdo->getAll($sql);
        $Count = $this->pdo->getRow($sqlcount);
        $recordCount = $Count['count'];
        $page=new pager_page($pageSize,$recordCount,$currentPage,$subPages,$page_info,4);
        $splitPageStr=$page->get_page_html();

        //关联用户信息
        $this->loadModel('sys_user');
        foreach ($res as $key=>$item){
            $res[$key]['user'] = $this->sys_user->getUserInfoById($item['create_uid']);
        }
        $result['list'] = $res;
        $result['pageStr'] = $splitPageStr;

        return $result;
    }

    /* 获取任务主体 */
    public function getTaskActionInfo($task_type,$action_id){
        switch ($task_type){
            case 'fc_esf' :
                $sql = "select a.id,a.build_no,a.unit_no,a.house_no,b.name from fc_esf as a left join fc_project as b on a.project_id=b.id where a.id={$action_id}";
                break;
            case 'fc_project':
                $sql = "select id,name from fc_project where id={$action_id}";
                break;
            default:
                break;
        }
        $rlt = $this->pdo->getRow($sql);
        switch ($task_type){
            case 'fc_esf' :
                $this->loadModel('fc_esf');
                $rlt['address']= $this->fc_esf->tranAddress($rlt['build_no'],$rlt['unit_no'],$rlt['house_no']);
                $rlt['action_name'] = $rlt['name'].$rlt['address'];
                break;
            case 'fc_project':
                $rlt['action_name'] = $rlt['name'];
                break;
            default:
                break;
        }
        //获取任务主体负责人列表
        $rlt['owner_list'] = $this->getTaskOwnerList($task_type);
        return $rlt;
    }

    /* 获取任务主体负责人列表 */
    public function getTaskOwnerList($task_type){
        //如果任务为房源、楼盘,则由指定的楼盘房源管理员复杂
        switch ($task_type){
            case 'fc_esf' :
                $owner_sql = "select id,true_name,user_name,user_type from sys_user where user_type=4";
                break;
            case 'fc_project':
                $owner_sql = "select id,true_name,user_name,user_type from sys_user where user_type=4";
                break;
            default:
                break;
        }
        $ownerList = $this->pdo->getAll($owner_sql);
        foreach ($ownerList as $item){
            $rlt[$item['id']]=$item['true_name'];
        }
        return $rlt;
    }

    /* 批量关闭任务 */
    public function updateTaskStatus(){}

}

